#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : light-edit
@File : ssh_scan.py
@Author : Yj
@Time : 2025/9/9
@脚本说明 : SSH 弱口令扫描模块
"""
import time
import paramiko
import threading

success_result = None


def ssh_connect(host, port, username, password):
    """尝试 SSH 连接，验证弱口令"""
    global success_result
    ssh = None
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print(f"尝试连接: IP={host}, 端口={port}, 用户名={username}, 密码={password}")
        ssh.connect(host, port, username, password, timeout=10)
        shell = ssh.invoke_shell()
        time.sleep(1)
        while shell.recv_ready():
            shell.recv(1024)
            time.sleep(0.1)
        shell.send("echo 'hello world'\n")
        time.sleep(1)
        if shell.recv_ready():
            output = shell.recv(1024).decode("utf-8", errors="replace")
            if "hello world" in output.lower().strip():
                print(f"[+] 连接成功！IP={host}, 用户名={username}, 密码={password}")
                success_result = ssh
                return ssh
        ssh.close()
    except:
        return None
    finally:
        if ssh and not success_result:
            ssh.close()


def read_file(file_path):
    """读取文件内容，忽略空行和注释"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = [line.strip() for line in f if line.strip() and not line.startswith('#')]
            if not lines:
                print(f"文件为空或无有效内容: {file_path}")
            return lines
    except Exception as e:
        print(f"读取文件时发生错误: {file_path}, 错误: {e}")
        return []


def ssh_run(ip_list_file, port, username_file, password_file):
    """扫描指定 IP 列表的 SSH 弱口令"""
    try:
        ip_list = read_file(ip_list_file)
        if not ip_list:
            print("IP列表为空，程序退出")
            return
        usernames = read_file(username_file)
        passwords = read_file(password_file)
        if not usernames or not passwords:
            print("用户名或密码列表为空，程序退出")
            return
        for host in ip_list:
            print(f"\n开始扫描 IP: {host}")
            global success_result
            success_result = None
            threads = []
            for username in usernames:
                for password in passwords:
                    t = threading.Thread(target=ssh_connect, args=(host, port, username, password))
                    t.start()
                    threads.append(t)
                    time.sleep(3)
                    if success_result:
                        success_result.close()
                        return
            for t in threads:
                t.join()
            print(f"IP={host} 的所有用户名和密码组合均失败")
        print("\n所有IP的用户名和密码组合均失败")
    except Exception as e:
        print(f"发生错误：{e}")
